package org.soaism.ui.wizard;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.log4j.Logger;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.internal.xtend.type.impl.java.JavaBeansMetaModel;
import org.eclipse.xpand2.XpandExecutionContextImpl;
import org.eclipse.xpand2.XpandFacade;
import org.eclipse.xpand2.output.Outlet;
import org.eclipse.xpand2.output.OutputImpl;
import org.osgi.framework.Bundle;

/**
 * @author wuendsch
 * 
 */
public class MySOADslProjectCreator extends SOADslProjectCreator {
	
//	private final String BUNDLE_NAME = "iphonical.ui";
//	private final String TEMPLATEDIR_PATH = "/templates/";

//	private final String DEST_XCODE_PROJ_NAME_ENDING = "_Project";

//	public static String current_template;

//	public static final String TEMPLATE_NAME_VIEW_BASED = "view_based";
//	public static final String TEMPLATE_NAME_NAV_BASED = "navigation_based";
//	public static final String TEMPLATE_NAME_TABBAR_BASED = "tabBar_based";

//	private final static Logger logger = Logger.getLogger(MySOADslProjectCreator.class);
	
//	@Override
//	protected void execute(final IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException {
//		monitor.beginTask("Creating model project " + getProjectInfo().getProjectName(), 3);
//
//		final IProject project = createProject(monitor);
//		monitor.worked(1);
//		if (project == null)
//			return;
//
//		initializeProject(project, monitor);
//		monitor.worked(1);
//
//		IFile modelFile = getModelFile(project);
//		setResult(modelFile);
//		// monitor.worked(1);
//
//		try {
//			String destination = project.getWorkspace().getRoot().getLocation().toOSString();
//			copyDirectory(TEMPLATEDIR_PATH + current_template, destination + "/"
//					+ current_template.replace(current_template, getProjectInfo().getProjectName() + DEST_XCODE_PROJ_NAME_ENDING));
//			monitor.worked(1);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
//
//	/**
//	 * copy a directory recursive and renaming the file-/directoryname to
//	 * projectname + {@link #DEST_XCODE_PROJ_NAME_ENDING}
//	 * 
//	 * @param srcPath
//	 *            path in the bundle {@link #BUNDLE_NAME}
//	 * @param dstPath
//	 *            path in the workspace of the new created project
//	 * @throws IOException
//	 * @throws URISyntaxException
//	 */
//	public void copyDirectory(String srcPath, String dstPath) throws IOException, URISyntaxException {
//
//		File src = new File(FileLocator.toFileURL(new URL("platform:/plugin/" + BUNDLE_NAME + srcPath)).toURI());
//		File dst = new File(dstPath);
//		// no hidden files or dirs but the hidden .projectFile to identify it as an eclipse project
//		if (!src.isHidden() || src.getName().endsWith(".project") ) {
//			if (src.isDirectory()) {
//				if (!dst.exists()) {
//					dst.mkdir();
//				}
//				String files[] = src.list();
//				for (String file : files) {
//					copyDirectory(srcPath + "/" + file, dstPath + "/" + file.replace(current_template, getProjectInfo().getProjectName()));
//				}
//
//			} else {
//				copyFile(srcPath, dstPath);
//			}
//		}
//	}
//
//	/**
//	 * copy a file and replace all occurence from old template name with new
//	 * projectname
//	 * 
//	 * @param fromPath
//	 *            path of file in the bundle {@link #BUNDLE_NAME}
//	 * @param toPath
//	 *            path of file (workspace of the new created project)
//	 * @throws IOException
//	 */
//	protected void copyFile(String fromPath, String toPath) throws IOException {
//		
//		if (logger.isDebugEnabled()) {
//			logger.debug("copy " + fromPath + "=>" + toPath);
//		}
//		InputStream from = null;
//		FileOutputStream to = null;
//		try {
//
//			Bundle b = Platform.getBundle(BUNDLE_NAME);
//			IPath path = new Path(fromPath);
//			from = FileLocator.openStream(b, path, false);
//			String s;
//			to = new FileOutputStream(toPath);
//			// Create output stream
//			byte[] buffer = new byte[4096]; // To hold file contents
//			int bytes_read; // How many bytes in buffer
//
//			// not efficient but we don't need a Script
//			while ((bytes_read = from.read(buffer)) != -1) {
//				// Read until EOF
//				s = new String(buffer);
//				if (s.length() > bytes_read) {
//					s = s.substring(0, bytes_read);
//				}
//				s = s.replace(current_template, getProjectInfo().getProjectName());
//				to.write(s.getBytes()); // write
//			}
//
//		} catch (IOException e) {
//		} finally {
//			if (from != null) {
//				from.close();
//			}
//			if (to != null) {
//				to.close();
//			}
//		}
//	}
	
	/**
	 * muss überschrieben werden, da iphonical.project in UTF-8(oder MacRoman) erzeugt werden muss
	 */
	@Override
	protected void initializeProject(final IProject project, final IProgressMonitor monitor) throws CoreException {
		final String encoding = "UTF-8";
		OutputImpl output = new OutputImpl();
		output.addOutlet(new Outlet(false, encoding, null, true, project.getLocation().makeAbsolute().toOSString()));

		XpandExecutionContextImpl execCtx = new XpandExecutionContextImpl(output, null);
		execCtx.setFileEncoding(encoding);
		execCtx.registerMetaModel(new JavaBeansMetaModel());

		XpandFacade facade = XpandFacade.create(execCtx);
		facade.evaluate("org::iphonical::ui::wizard::SOADSLNewProject::main", getProjectInfo());

		project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
	}
	
	
	

}
